package com.wodsy.phoenix.datadao.shopc.dao.impl;

import com.wodsy.phoenix.datadao.base.BaseHibernateDao;
import com.wodsy.phoenix.datadao.shopc.dao.ShopDao;
import com.wodsy.phoenix.dataobject.base.Pager;
import com.wodsy.phoenix.dataobject.shopc.model.Shop;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import java.util.Date;

@Repository("shopDao")
public class ShopDaoImpl extends BaseHibernateDao<Shop, Integer> implements ShopDao {
	@Autowired
	@Qualifier(value="shopc")
	@Override
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public Class<Shop> getModelClass() {
		return Shop.class;
	}
	
	@Override
	public void delShop(Integer shopId){
		String hql = "update Shop shop set shop.deleted = :deleted,shop.deleteTime = :deleteTime,shop.updateTime = :updateTime where shop.id = :shopId";
		Query query = getSession().createQuery(hql);
		query.setBoolean("deleted", true);
		query.setTimestamp("deleteTime", new Date());
		query.setTimestamp("updateTime", new Date());
		query.setInteger("shopId", shopId);
		query.executeUpdate();
	}

	@Override
	public Pager<Shop> findShop(Pager<Shop> pager) {
		Criteria criteria = getSession().createCriteria(getModelClass());
		criteria.addOrder(Order.desc("createTime"));
		return toPager(pager, criteria);
	}
	
	@Override
	public void openShop(Integer shopId){
		String hql = "update Shop shop set shop.shutdowned = :shutdowned,shop.openTime = :openTime,shop.updateTime = :updateTime where shop.id = :shopId";
		Query query = getSession().createQuery(hql);
		query.setBoolean("shutdowned", false);
		query.setTimestamp("openTime", new Date());
		query.setTimestamp("updateTime", new Date());
		query.setInteger("shopId", shopId);
		query.executeUpdate();
	}
	
	@Override
	public void closeShop(Integer shopId){
		String hql = "update Shop shop set shop.shutdowned = :shutdowned,shop.closeTime = :closeTime,shop.updateTime = :updateTime where shop.id = :shopId";
		Query query = getSession().createQuery(hql);
		query.setBoolean("shutdowned", true);
		query.setTimestamp("closeTime", new Date());
		query.setTimestamp("updateTime", new Date());
		query.setInteger("shopId", shopId);
		query.executeUpdate();
	}

}
